package com.laundry.user.ui.home

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.laundry.user.data.model.ServiceCategory
import com.laundry.user.data.model.Merchant
import com.laundry.user.data.repository.MerchantRepository
import com.laundry.user.ui.search.SearchActivity
import com.laundry.user.ui.merchant.MerchantListActivity
import kotlinx.coroutines.launch

class HomeFragment : Fragment() {

    private lateinit var merchantRepository: MerchantRepository
    private lateinit var searchEditText: EditText
    private lateinit var categoriesRecyclerView: RecyclerView
    private lateinit var merchantsRecyclerView: RecyclerView
    private lateinit var categoriesAdapter: CategoriesAdapter
    private lateinit var merchantsAdapter: MerchantsAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        merchantRepository = MerchantRepository(requireContext())
        return createView()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupAdapters()
        loadData()
    }

    private fun createView(): View {
        val scrollView = ScrollView(requireContext()).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }

        val mainLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(16, 16, 16, 16)
        }

        // 搜索栏
        val searchLayout = createSearchLayout()
        
        // 服务分类标题
        val categoriesTitle = TextView(requireContext()).apply {
            text = "服务分类"
            textSize = 18f
            setTextColor(android.graphics.Color.parseColor("#333333"))
            setPadding(0, 24, 0, 16)
        }

        // 服务分类网格
        categoriesRecyclerView = RecyclerView(requireContext()).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutManager = GridLayoutManager(requireContext(), 4)
        }

        // 推荐商家标题
        val merchantsTitle = TextView(requireContext()).apply {
            text = "推荐商家"
            textSize = 18f
            setTextColor(android.graphics.Color.parseColor("#333333"))
            setPadding(0, 24, 0, 16)
        }

        // 推荐商家列表
        merchantsRecyclerView = RecyclerView(requireContext()).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutManager = LinearLayoutManager(requireContext())
            isNestedScrollingEnabled = false
        }

        mainLayout.addView(searchLayout)
        mainLayout.addView(categoriesTitle)
        mainLayout.addView(categoriesRecyclerView)
        mainLayout.addView(merchantsTitle)
        mainLayout.addView(merchantsRecyclerView)

        scrollView.addView(mainLayout)
        return scrollView
    }

    private fun createSearchLayout(): LinearLayout {
        val searchLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.HORIZONTAL
            setPadding(0, 0, 0, 0)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
        }

        searchEditText = EditText(requireContext()).apply {
            hint = "搜索商家或服务"
            setPadding(20, 20, 20, 20)
            background = createSearchBackground()
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        val searchButton = Button(requireContext()).apply {
            text = "搜索"
            setPadding(20, 20, 20, 20)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                marginStart = 12
            }
            background = createButtonBackground()
            setTextColor(android.graphics.Color.WHITE)
            setOnClickListener {
                val keyword = searchEditText.text.toString().trim()
                if (keyword.isNotEmpty()) {
                    val intent = Intent(requireContext(), SearchActivity::class.java)
                    intent.putExtra("keyword", keyword)
                    startActivity(intent)
                }
            }
        }

        searchLayout.addView(searchEditText)
        searchLayout.addView(searchButton)
        return searchLayout
    }

    private fun setupAdapters() {
        categoriesAdapter = CategoriesAdapter { category ->
            val intent = Intent(requireContext(), MerchantListActivity::class.java)
            intent.putExtra("category_id", category.id)
            intent.putExtra("category_name", category.name)
            startActivity(intent)
        }
        categoriesRecyclerView.adapter = categoriesAdapter

        merchantsAdapter = MerchantsAdapter { merchant ->
            // TODO: 跳转到商家详情页
            Toast.makeText(requireContext(), "点击了商家: ${merchant.name}", Toast.LENGTH_SHORT).show()
        }
        merchantsRecyclerView.adapter = merchantsAdapter
    }

    private fun loadData() {
        loadCategories()
        loadMerchants()
    }

    private fun loadCategories() {
        lifecycleScope.launch {
            merchantRepository.getServiceCategories().collect { categories ->
                categoriesAdapter.updateData(categories)
            }
        }
    }

    private fun loadMerchants() {
        lifecycleScope.launch {
            val result = merchantRepository.getMerchants(
                page = 1,
                size = 10,
                sort = "rating"
            )
            
            if (result.isSuccess) {
                val merchants = result.getOrNull()?.items ?: emptyList()
                merchantsAdapter.updateData(merchants)
            } else {
                Toast.makeText(
                    requireContext(),
                    "加载商家失败: ${result.exceptionOrNull()?.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun createSearchBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.parseColor("#F5F5F5"))
        drawable.setStroke(1, android.graphics.Color.parseColor("#E0E0E0"))
        drawable.cornerRadius = 8f
        return drawable
    }

    private fun createButtonBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.parseColor("#2196F3"))
        drawable.cornerRadius = 8f
        return drawable
    }
}

// 服务分类适配器
class CategoriesAdapter(
    private val onItemClick: (ServiceCategory) -> Unit
) : RecyclerView.Adapter<CategoriesAdapter.ViewHolder>() {

    private var categories = listOf<ServiceCategory>()

    fun updateData(newCategories: List<ServiceCategory>) {
        categories = newCategories
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LinearLayout(parent.context).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(16, 16, 16, 16)
            gravity = android.view.Gravity.CENTER
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                200
            )
            background = createItemBackground()
        }

        val iconView = ImageView(parent.context).apply {
            layoutParams = LinearLayout.LayoutParams(60, 60)
            setImageResource(android.R.drawable.ic_menu_gallery)
        }

        val nameView = TextView(parent.context).apply {
            textSize = 14f
            gravity = android.view.Gravity.CENTER
            setPadding(0, 8, 0, 0)
            setTextColor(android.graphics.Color.parseColor("#333333"))
        }

        itemView.addView(iconView)
        itemView.addView(nameView)

        return ViewHolder(itemView, iconView, nameView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val category = categories[position]
        holder.nameView.text = category.name
        holder.itemView.setOnClickListener { onItemClick(category) }
    }

    override fun getItemCount() = categories.size

    private fun createItemBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.WHITE)
        drawable.setStroke(1, android.graphics.Color.parseColor("#E0E0E0"))
        drawable.cornerRadius = 8f
        return drawable
    }

    class ViewHolder(
        val itemView: View,
        val iconView: ImageView,
        val nameView: TextView
    ) : RecyclerView.ViewHolder(itemView)
}

// 商家适配器
class MerchantsAdapter(
    private val onItemClick: (Merchant) -> Unit
) : RecyclerView.Adapter<MerchantsAdapter.ViewHolder>() {

    private var merchants = listOf<Merchant>()

    fun updateData(newMerchants: List<Merchant>) {
        merchants = newMerchants
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LinearLayout(parent.context).apply {
            orientation = LinearLayout.HORIZONTAL
            setPadding(16, 16, 16, 16)
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            background = createItemBackground()
        }

        val avatarView = ImageView(parent.context).apply {
            layoutParams = LinearLayout.LayoutParams(80, 80)
            setImageResource(android.R.drawable.ic_menu_gallery)
        }

        val infoLayout = LinearLayout(parent.context).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(16, 0, 0, 0)
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        val nameView = TextView(parent.context).apply {
            textSize = 16f
            setTextColor(android.graphics.Color.parseColor("#333333"))
        }

        val addressView = TextView(parent.context).apply {
            textSize = 14f
            setTextColor(android.graphics.Color.parseColor("#666666"))
            setPadding(0, 4, 0, 0)
        }

        val ratingView = TextView(parent.context).apply {
            textSize = 14f
            setTextColor(android.graphics.Color.parseColor("#FF9800"))
            setPadding(0, 4, 0, 0)
        }

        infoLayout.addView(nameView)
        infoLayout.addView(addressView)
        infoLayout.addView(ratingView)

        itemView.addView(avatarView)
        itemView.addView(infoLayout)

        return ViewHolder(itemView, avatarView, nameView, addressView, ratingView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val merchant = merchants[position]
        holder.nameView.text = merchant.name
        holder.addressView.text = merchant.address
        holder.ratingView.text = "⭐ ${merchant.rating} (${merchant.reviewCount}条评价)"
        holder.itemView.setOnClickListener { onItemClick(merchant) }
    }

    override fun getItemCount() = merchants.size

    private fun createItemBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.WHITE)
        drawable.setStroke(1, android.graphics.Color.parseColor("#E0E0E0"))
        drawable.cornerRadius = 8f
        return drawable
    }

    class ViewHolder(
        val itemView: View,
        val avatarView: ImageView,
        val nameView: TextView,
        val addressView: TextView,
        val ratingView: TextView
    ) : RecyclerView.ViewHolder(itemView)
}
